package com.ly.mpayment.rest.system;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ly.mpayment.core.util.BigUtil;
import com.ly.mpayment.core.util.Config;
import com.ly.mpayment.core.util.DateUtils;
import com.ly.mpayment.core.util.JsonUtils;
import com.ly.mpayment.core.util.ResultMessage;
import com.ly.mpayment.core.util.UserUtil;
import com.ly.mpayment.persist.entity.PlatFormAccount;
import com.ly.mpayment.persist.entity.PlatFormAccountRecord;
import com.ly.mpayment.persist.entity.User;
import com.ly.mpayment.persist.service.platformaccount.IPlatformAccountService;
import com.ly.mpayment.persist.service.platformaccountrecord.IPlatFormAccountRecordService;
import com.ly.mpayment.persist.service.user.IUserService;
import com.ly.mpayment.rest.AbsRest;

import net.sf.json.JSONObject;

@Component
@Path("system/platformaccouont/")
public class PlatFormAccountRest extends AbsRest{

	@Autowired
	IUserService userService;

	@Autowired
	IPlatformAccountService accountService;

	@Autowired
	IPlatFormAccountRecordService recordService;

	@SuppressWarnings("static-access")
	@POST
	@Path("addPlatFormAccount")
	public String addPlatFormAccount(String data,@Context HttpServletRequest request){
		String result = this.validationParameter(data, request, userService, "price","remark");
		if(result == null){
			JSONObject json = JSONObject.fromObject(data);
			PlatFormAccount account = accountService.findByAccount();
			if(account != null){
				account.setPlatformamount(account.getPlatformamount().subtract(BigUtil.getBigDecimal(json.getString("price"))));
				PlatFormAccountRecord record = new PlatFormAccountRecord();
				record.setChangeamount(BigUtil.getBigDecimal(json.getString("price")));
				record.setChangetime(DateUtils.getNowDate());
				record.setPayType(Config.payMent);
				record.setPlatFormAccount(account);
				record.setRemark(json.getString("remark"));
				String token = request.getHeader("token");
				if (token != null) {
					DecodedJWT jwt;
					try {
						jwt = JWT.decode(token);
						if (jwt != null) {
							JSONObject jsons = JsonUtils.converToJson(jwt.getSubject());
							if (json != null) {
								User login = userService.findByUserid(jsons.getString(Config.tokenSignAttr));
								if(login != null && UserUtil.checkRole(login)){
									record.setUser(login);
									this.recordService.addPlatformaccountrecord(record);
									this.accountService.updatePlatformaccount(account);
									return ResultMessage.getSucceed(null);
								}
							}
						}
					}catch(Exception e){
						e.printStackTrace();
					}
				}
			}
			return ResultMessage.getFailt(ResultMessage.initAccountError);
		}
		return result;
	}
}
